//
//  DownLoadViewController.m
//  CapriceMusic
//
//  Created by dllo on 16/1/11.
//  Copyright © 2016年 MYX. All rights reserved.
//

#import "DownLoadViewController.h"
#import "DataBaseHandle.h"
#import "DownloadTableViewCell.h"
#import "CustomPlayerViewController.h"
#import "AppDelegate.h"
#import "DownLoadManager.h"
#import "FavoritesTableViewCell.h"
@interface DownLoadViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UISegmentedControl *segmentControl;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *downLoading;

@property (nonatomic, strong) DataBaseHandle *dataBaseHandle;

@property (nonatomic, assign) CGFloat num;

@end

static DownLoadViewController *downLoadManager = nil;

@implementation DownLoadViewController

+ (instancetype)shareDownLoadManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        downLoadManager = [[DownLoadViewController alloc] init];
    });
    return downLoadManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"下载的MV";
    self.segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"已下载",@"正在下载"]];
    _segmentControl.frame = CGRectMake(self.view.frame.size.width / 10, 0, self.view.frame.size.width * 0.8, 30);
    _segmentControl.tintColor = [UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0];
    self.segmentControl.selectedSegmentIndex = 1;
    [self.segmentControl addTarget:self action:@selector(segmentControlDidPress) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segmentControl];
    
    self.dataBaseHandle = [DataBaseHandle shareDataBase];
    [self.dataBaseHandle openDataBase];
    [self.dataBaseHandle selectdownloading];
    [self.dataBaseHandle closedDataBase];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 35, self.view.frame.size.width, self.view.frame.size.height - 99) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tag = 101;
    [self.tableView registerClass:[DownloadTableViewCell class] forCellReuseIdentifier:@"DownLoadingIdentifier"];
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[FavoritesTableViewCell class] forCellReuseIdentifier:@"FavoritesTableViewCellIdentifier"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"progress" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endTask:) name:@"end" object:nil];
}

- (void)change:(NSNotification *)message {
    NSString *str = message.object;
    self.num = str.floatValue;
    [self.tableView reloadData];
}

- (void)endTask:(NSNotification *)message {
    [ProgressHUD showSuccess:@"下载完成"];
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.segmentControl.selectedSegmentIndex == 0) {
        return self.dataBaseHandle.downloadAlreadyAddress.count;
    } else {
    return self.dataBaseHandle.downloadingTitle.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.segmentControl.selectedSegmentIndex == 0) {
        FavoritesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FavoritesTableViewCellIdentifier"];
        cell.mytitle.text = self.dataBaseHandle.downloadAlreadyTitle[indexPath.row];
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:self.dataBaseHandle.downloadAlreadyPicture[indexPath.row]]];
        return cell;
    } else {
        DownloadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DownLoadingIdentifier"];
        [cell.coverPic sd_setImageWithURL:[NSURL URLWithString:self.dataBaseHandle.downloadingPicture[indexPath.row]]];
        cell.titleLabel.text = self.dataBaseHandle.downloadingTitle[indexPath.row];
        cell.progressView.progress = self.num;
        cell.progressLabel.text = [NSString stringWithFormat:@"已完成%ld%%",(NSInteger)(self.num * 100)];
        return cell;
    }
}

- (void)segmentControlDidPress {
    self.dataBaseHandle = [DataBaseHandle shareDataBase];
    if (self.segmentControl.selectedSegmentIndex == 0) {
        [self.dataBaseHandle openDataBase];
        [self.dataBaseHandle createDownloadAlreadyTable];
        [self.dataBaseHandle selectdownloadAlready];
        [self.dataBaseHandle closedDataBase];
        [self.tableView reloadData];
    } else {
        [self.dataBaseHandle openDataBase];
        [self.dataBaseHandle createDownloadingTable];
        [self.dataBaseHandle selectdownloading];
        [self.dataBaseHandle closedDataBase];
        [self.tableView reloadData];
    }
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
        [self.dataBaseHandle openDataBase];
    if (self.segmentControl.selectedSegmentIndex == 0) {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:self.dataBaseHandle.downloadAlreadyAddress[indexPath.row] error:nil];
        [self.dataBaseHandle.downloadAlreadyTitle removeObjectAtIndex:indexPath.row];
        [self.dataBaseHandle.downloadAlreadyPicture removeObjectAtIndex:indexPath.row];
        [self.dataBaseHandle deleteDownloadAlready:self.dataBaseHandle.downloadAlreadyAddress[indexPath.row]];
        [self.dataBaseHandle selectdownloadAlready];
        [self.dataBaseHandle closedDataBase];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        [ProgressHUD showSuccess:@"视频删除成功"];
    } else  {
        DownLoadManager *downLoad = [DownLoadManager shareDownLoadManager];
        [self.dataBaseHandle deleteDownloading:self.dataBaseHandle.downloadingTitle[0]];
        [self.dataBaseHandle.downloadingTitle removeObjectAtIndex:indexPath.row];
        [self.dataBaseHandle.downloadingPicture removeObjectAtIndex:indexPath.row];
        [self.dataBaseHandle selectdownloading];
        [self.dataBaseHandle closedDataBase];
        [downLoad.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            [downLoad setResumeData:resumeData];
            downLoad.downloadTask = nil;
        }];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        downLoad.isdownloading = NO;
        [ProgressHUD showSuccess:@"当前下载任务已删除"];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.segmentControl.selectedSegmentIndex == 0) {
        CustomPlayerViewController *custom = [[CustomPlayerViewController alloc] init];
        custom.filePath = [NSString stringWithFormat:@"file://%@",self.dataBaseHandle.downloadAlreadyAddress[indexPath.row]];
        custom.isLocal = YES;
        custom.navigationItem.title = self.dataBaseHandle.downloadAlreadyTitle[indexPath.row];
        [self presentViewController:custom animated:YES completion:nil];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return self.view.frame.size.height / 5;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC setPanEnabled:NO];
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
